#include "filewriter.h"
#include "metainfo.h"
#include <QDebug>
#include<QDir>

FileWriter::FileWriter(const MetaInfo &fileInfo, const QDir& path, QObject *parent)
    : QObject(parent), readBuffer(NULL), isDownloaded(false)
{
    fileMetaInfo = fileInfo;
    MetaInfoSingleFile singleFile = fileInfo.singleFile();
    QString fileName = singleFile.name;
    fileName.prepend( path.absolutePath() + "/");
    file = new QFile(fileName, this);
}
FileWriter::~FileWriter()
{
    delete readBuffer;
    if (!isDownloaded)
    {
        bool result = file->remove();
        qDebug() << "FileWriter: removing file, result: " << result;
    }
}

void FileWriter::createAndOpenFile()
{
    if(!file->open(QFile::ReadWrite))
    {        
    emit error("Could not open file, error: " +
                   QString::number(file->error()));
    }
    if (!file->resize(fileMetaInfo.totalSize()) )
    {
        emit error("Could not resize file, error: " +
                   QString::number(file->error()));
    }
}
void FileWriter::writeToFile(int offset, const QByteArray& data)
{
    qDebug() << "FileWriter::writeData: offset =  "
             << offset;
    if(!file->seek(offset))
    {
        emit error("File access error: " +
                   QString::number(file->error()));
        return;
    }
    int bytesWritten = file->write(data);
    qDebug() << "written " << bytesWritten << " bytes";
    if (-1 == bytesWritten)
    {
        emit error("File write error: " +
                   QString::number(file->error()));
    }
}
void FileWriter::closeFile()
{
    file->close();
}
const QByteArray& FileWriter::readFromFile(int offset, quint32 size)
{
    qDebug() << "FileWriter::readFromFile: offset" << offset << ", size: " << size;
    delete readBuffer;
    readBuffer = NULL;
    if(!file->seek(offset))
    {
        emit error("File access error: " +
                   QString::number(file->error()));
        return *readBuffer;  //TODO dangerous
    }
    readBuffer = new QByteArray(size, '\0');
    qint64 bytesRead = file->read(readBuffer->data(), size);
    qDebug() << "bytes read: " << bytesRead;
    return *readBuffer;

}
void FileWriter::setFileDownloaded(bool downloaded)
{
    isDownloaded = downloaded;
}
